package io.renren.modules.app.config;

import com.baidu.aip.ocr.AipOcr;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.modules.app.entity.VehicleEntity;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther zxl
 * @Date 2019/1/13 15:20
 * @Description
 **/
@ConfigurationProperties(prefix = "baidu.vehicle-ocr")
@Component
public class BaiduOCRConfig {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private String oauthURL;

    private String grant_type;

    private String app_id;

    private String client_id;

    private String client_secret;

    private String corURL;

    /**
     * 行驶证识别
     * @param imgURL
     * @return
     * 百度云识别结果:{"log_id":1110791496503564944,"error_msg":"recognize error, failed to match the template","error_code":282103}
     */
    public R ocr(String imgURL){
        HashMap<String, String> options = new HashMap<String, String>(2);
        options.put("accuracy","normal");
        System.out.println(this.toString());
        AipOcr client = new AipOcr(this.getApp_id(), this.getClient_id(), this.getClient_secret());
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        JSONObject jsonObject = client.vehicleLicense(imgURL, options);
        System.err.println("百度云识别结果:"+jsonObject.toString());
        Integer words_result_num;
        try{
            words_result_num = jsonObject.getInt("words_result_num");
        }catch (JSONException e){
            e.printStackTrace();
            Integer error_code = jsonObject.getInt("error_code");
            return R.error(error_code+",图片识别错误！");
        }
        if (words_result_num == null || words_result_num<10){
            return R.error("照片识别失败");
        }
        JSONObject words_result = jsonObject.getJSONObject("words_result");
        String vin = words_result.getJSONObject("车辆识别代号").getString("words");
        String plate_num = words_result.getJSONObject("号牌号码").getString("words");
        String vehicle_type = words_result.getJSONObject("车辆类型").getString("words");
        String owner = words_result.getJSONObject("所有人").getString("words");
        String use_character = words_result.getJSONObject("使用性质").getString("words");
        String addr = words_result.getJSONObject("住址").getString("words");
        String model = words_result.getJSONObject("品牌型号").getString("words");
        String engine_num = words_result.getJSONObject("发动机号码").getString("words");

        JSONObject register_date_json;
        try{
            register_date_json = words_result.getJSONObject("注册日期");
        }catch (JSONException e){
            e.printStackTrace();
            register_date_json = words_result.getJSONObject("注册登记日期");
        }

        Date register_date = DateUtils.
                stringToDate(register_date_json.getString("words"),"yyyyMMdd") ;
        Date issue_date = DateUtils.
                stringToDate(words_result.getJSONObject("发证日期").getString("words"),"yyyyMMdd");
        VehicleEntity vehicleEntity = new VehicleEntity(plate_num,vehicle_type,owner,use_character,addr,model,vin
                                                        ,engine_num,register_date,issue_date,true);
        System.out.println("结果封装："+vehicleEntity.toString());
        return R.ok().put("data",vehicleEntity);
    }

    /**
     * 获取Access_token
     * @return
     */
    public String getAuth(){
        String authHost = this.getOauthURL();
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type="+this.getGrant_type()
                // 2. 官网获取的 API Key
                + "&client_id=" + this.getClient_id()
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + this.getClient_secret();
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.err.printf("获取token失败！");
            e.printStackTrace();
        }
        return null;
    }

    public String getApp_id() {
        return app_id;
    }

    public void setApp_id(String app_id) {
        this.app_id = app_id;
    }

    public String getOauthURL() {
        return oauthURL;
    }

    public void setOauthURL(String oauthURL) {
        this.oauthURL = oauthURL;
    }

    public String getGrant_type() {
        return grant_type;
    }

    public void setGrant_type(String grant_type) {
        this.grant_type = grant_type;
    }

    public String getClient_id() {
        return client_id;
    }

    public void setClient_id(String client_id) {
        this.client_id = client_id;
    }

    public String getClient_secret() {
        return client_secret;
    }

    public void setClient_secret(String client_secret) {
        this.client_secret = client_secret;
    }

    public String getCorURL() {
        return corURL;
    }

    public void setCorURL(String corURL) {
        this.corURL = corURL;
    }

    @Override
    public String toString() {
        return "BaiduOCRConfig{" +
                "oauthURL='" + oauthURL + '\'' +
                ", grant_type='" + grant_type + '\'' +
                ", app_id='" + app_id + '\'' +
                ", client_id='" + client_id + '\'' +
                ", client_secret='" + client_secret + '\'' +
                ", corURL='" + corURL + '\'' +
                '}';
    }
}
